package com.tzy.note.base.thread.create;

import com.tzy.note.base.util.Downloader;

import java.util.concurrent.*;

/**
 * 创建线程方式四：线程池
 * 使用线程池实现下载
 */
public class CreateThread4_DownLoader implements Callable {
    //线程池数量
    private static int POOL_NUM = 3;
    //网络资源url
    private String url;
    //保存的文件名(含路径)
    private String pathFileName;

    public CreateThread4_DownLoader(String url, String pathFileName){
        this.url = url;
        this.pathFileName = pathFileName;
    }

    @Override
    public Boolean call() throws Exception {
        if("tzy3".equals(Thread.currentThread().getName())){
            System.out.println("线程: " + Thread.currentThread().getName() + " 下载了" + pathFileName + "失败！");
            return false;
        }
        Downloader.download(url,pathFileName);
        System.out.println("线程: " + Thread.currentThread().getName() + " 下载了" + pathFileName + "成功！");
        return true;
    }

    public static void main(String[] args) throws Exception {
        CreateThread4_DownLoader cd1 = new CreateThread4_DownLoader("https://www.baidu.com/favicon.ico","1.ico");
        CreateThread4_DownLoader cd2 = new CreateThread4_DownLoader("https://www.baidu.com/img/flexible/logo/pc/result.png","2.png");
        CreateThread4_DownLoader cd3 = new CreateThread4_DownLoader("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/topnav/baiduyun@2x-e0be79e69e.png","3.png");
        //创建执行服务:
        ExecutorService executorService = Executors.newFixedThreadPool(POOL_NUM);
        //提交执行
        Future<Boolean> futureTask1 = executorService.submit(cd1);
        Future<Boolean> futureTask2 = executorService.submit(cd2);
        Future<Boolean> futureTask3 = executorService.submit(cd3);
        //获取结果
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());
        System.out.println(futureTask3.get());
        //关闭服务
        executorService.shutdownNow();
    }
}
